import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QScrollArea, QVBoxLayout, QWidget
from PySide6.QtGui import QPixmap, QImage, Qt
from PySide6.QtCore import Slot


class ImageWindow(QMainWindow):
    def __init__(self, image_path):
        super().__init__()

        # 加载图像
        self.pixmap = QPixmap(image_path)
        self.image_label = QLabel()
        self.image_label.setPixmap(
            self.pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

        # 设置滚动区域
        self.scroll_area = QScrollArea()
        # self.scroll_area.setBackgroundRole(Qt.LightBackground)
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.image_label)

        # 设置布局
        self.main_widget = QWidget()
        self.layout = QVBoxLayout(self.main_widget)
        self.layout.addWidget(self.scroll_area)
        self.setCentralWidget(self.main_widget)

        # 连接窗口大小改变信号到槽函数
        self.resizeEvent = self.on_resize

    @Slot()
    def on_resize(self, event):
        # 当窗口大小改变时，重新缩放图片
        self.update_image_size()

    def update_image_size(self):
        # 根据当前窗口宽度和原始图片宽高比缩放图片
        new_width = self.width()
        scaled_pixmap = self.pixmap.scaledToWidth(new_width, Qt.SmoothTransformation)
        self.image_label.setPixmap(scaled_pixmap)
        self.image_label.adjustSize()  # 调整标签大小以适应新图片大小


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 替换为你的图片路径
    image_path = "asset/gammaImg.png"

    window = ImageWindow(image_path)
    window.setWindowTitle("Image Viewer")
    window.show()

    sys.exit(app.exec())